<template>
  <div class="app-container">
    <div class="page-container">
      <div class="d-flex align-center ml-70 mb-30 mt-10">
        <span>实时统计：</span>
        <el-tag type="info" size="large" class="mr-12"
          >未打扫：{{ houseStatusNumObj.weiruzhu }}</el-tag
        >
        <el-tag type="success" size="large" class="mr-12"
          >可入住：{{ houseStatusNumObj.keruzhu }}</el-tag
        >
        <el-tag type="primary" size="large" class="mr-12"
          >已入住：{{ houseStatusNumObj.yiruzhu }}</el-tag
        >
        <el-tag type="danger" size="large"
          >维护中：{{ houseStatusNumObj.weihuzhong }}</el-tag
        >
      </div>
      <div class="d-flex">
        <div class="left-tabs mt-50" style="height: 100%">
          <el-tabs v-model="floorId" tab-position="left" @tab-change="getList">
            <el-tab-pane label="全部" :name="null"></el-tab-pane>
            <el-tab-pane
              v-for="item in floorAllList"
              :name="item.floorId"
              :label="item.floorNum"
            >
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="left-box" style="width: 100%">
          <div class="top-tabs">
            <el-tabs
              v-model="houseTypeId"
              tab-position="top"
              @tab-change="getList"
            >
              <el-tab-pane label="全部" :name="null"></el-tab-pane>
              <el-tab-pane
                v-for="item in houseTypeAllList"
                :name="item.houseTypeId"
                :label="item.houseTypeName"
              >
              </el-tab-pane>
            </el-tabs>
          </div>
          <div class="house-list d-flex flex-wrap">
            <el-card
              v-for="item in houseList"
              :key="item.houseId"
              style="width: 270px; height: 180px; color: #fff"
              :style="{ backgroundColor: backgroundColor[item.houseStatus] }"
              class="house-item p-rela mr-10 mb-10"
              @click="ruzhuDetail(item)"
            >
              <div class="d-flex justify-space-between align-center">
                <div>房号：{{ item.houseNum }}</div>
                <div>{{ item.houseTypeName }}</div>
              </div>
              <div class="mt-15 d-flex justify-space-between align-center">
                <dict-tag :options="house_status" :value="item.houseStatus" />
                <div v-if="item.houseStatus == 3" class="font-14">
                  入住人数: {{ item.peopleNumber }}
                </div>
              </div>
              <div
                class="actions p-abso font-24 d-flex justify-end align-center"
                style="bottom: 15px; right: 15px; width: 240px"
              >
                <img
                  v-show="item.houseStatus == 2"
                  src="@/assets/images/ruzhu.png"
                  title="入住"
                  @click.stop="ruzhu(item)"
                />
                <img
                  v-show="item.houseStatus == 3"
                  src="@/assets/images/tuifang.png"
                  title="离店"
                  @click.stop="tuifang(item)"
                />
                <el-dropdown
                  trigger="click"
                  @command="
                    (command) => {
                      gengxin(item, command)
                    }
                  "
                >
                  <img
                    v-show="item.houseStatus != 3"
                    title="更新状态"
                    src="@/assets/images/gengxin.png"
                  />
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="2">可入住</el-dropdown-item>
                      <el-dropdown-item command="1">未打扫</el-dropdown-item>
                      <el-dropdown-item command="4">维护中</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </div>
    <el-dialog :title="title" v-model="open" width="960px" append-to-body>
      <el-form
        ref="checkInHotelRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="mt-20"
      >
        <div class="house-info mb-20 font-30">
          <el-alert type="success" :closable="false">
            <template #title>
              <el-row class="pt-20">
                <el-form-item label="房间号">
                  {{ form.houseNum }}
                </el-form-item>
                <el-form-item label="房型">
                  {{ form.houseTypeName }}
                </el-form-item>
              </el-row>
            </template>
          </el-alert>
        </div>

        <el-form-item label="开房时间" prop="createTime">
          <el-date-picker
            v-model="form.createTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开房时间"
            :disabled="true"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="人员信息" prop="hotelCheckRecordList">
          <div class="dengji-table d-flex">
            <el-table
              :data="form.hotelCheckRecordList"
              style="width: 100%"
              height="250"
            >
              <el-table-column prop="realName" label="姓名" width="150">
                <template #default="scope">
                  <el-form-item
                    :prop="`hotelCheckRecordList[${scope.$index}].realName`"
                    :rules="[
                      {
                        required: true,
                        message: '请填写姓名',
                        trigger: 'blur'
                      }
                    ]"
                  >
                    <el-input v-model="scope.row.realName"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="idCard" label="身份证号" width="200">
                <template #default="scope">
                  <el-form-item
                    :prop="`hotelCheckRecordList[${scope.$index}].realName`"
                    :rules="[
                      {
                        required: true,
                        message: '请填写身份证号',
                        trigger: 'blur'
                      }
                    ]"
                  >
                    <el-input v-model="scope.row.idCard"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="phone" label="手机号" width="150">
                <template #default="scope">
                  <el-form-item
                    :prop="`hotelCheckRecordList[${scope.$index}].phone`"
                  >
                    <el-input v-model="scope.row.phone"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
                width="200"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <el-button link type="primary" @click="readCard(scope.$index)"
                    >读取身份证</el-button
                  >
                  <el-button
                    link
                    type="danger"
                    @click="handleDelete(scope.row, scope.$index)"
                    >移除</el-button
                  >
                </template>
              </el-table-column>
              <template #empty><span></span></template>
            </el-table>
            <el-button
              type="success"
              plain
              @click="addPeople"
              class="ml-20 mt-5"
              >添加</el-button
            >
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancel">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CheckInHotel">
import { listFloorAll } from '@/api/hotel/floor'
import { listHouseTypeAll } from '@/api/hotel/houseType'
import {
  houseAllList,
  changeHouseStatus,
  getHouseDetail,
  addHouseRecord,
  updateHouseRecord,
  confirmCheckOut,
  getHouseStatusNumber,
  deleteCheckInPeople
} from '@/api/hotel/houseRecord'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

const { proxy } = getCurrentInstance()
const { house_status } = proxy.useDict('house_status')
const checkInHotelRef = ref(null)
const houseList = ref([])
const open = ref(false)
const loading = ref(true)
const title = ref('')
const floorAllList = ref([])
const houseTypeAllList = ref([])
const floorId = ref(null)
const houseTypeId = ref(null)
const isDisabled = ref(false)
const houseStatusNumObj = ref({})
const deleteHotelCheckRecordList = ref([])
let websockets = null
let isconncet = false
const backgroundColor = ref({
  1: '#909399',
  2: '#67C23A',
  3: '#409EFF',
  4: '#F56C6C'
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    houseTypeName: null
  },
  rules: {
    createTime: [
      { required: true, message: '开房时间不能为空', trigger: 'blur' }
    ],
    hotelCheckRecordList: [
      { required: true, message: '人员信息不能为空', trigger: 'blur' }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

function getFloorAll() {
  listFloorAll().then((res) => {
    floorAllList.value = res.data
  })
}

function getHouseTypeAll() {
  listHouseTypeAll().then((res) => {
    houseTypeAllList.value = res.data
  })
}

function ruzhu(data) {
  OcrRecognition()
  getHouseDetail(data.houseId).then((res) => {
    form.value = {
      ...res.data,
      houseId: data.houseId,
      houseNum: data.houseNum,
      houseTypeName: data.houseTypeName,
      createTime: new Date()
    }
    open.value = true
    addPeople()
    title.value = '入住登记'
  })
  isDisabled.value = false
}
function ruzhuDetail(data) {
  if (data.houseStatus != 3) {
    return
  }
  OcrRecognition()
  deleteHotelCheckRecordList.value = []
  getHouseDetail(data.houseId).then((res) => {
    res.data.hotelCheckRecordList.forEach((item) => {
      item.updateIdentify = 2
    })
    form.value = {
      ...res.data,
      houseId: data.houseId,
      houseNum: data.houseNum,
      houseTypeName: data.houseTypeName,
      createTime: res.data.createTime
    }
    open.value = true
    title.value = '入住详情'
  })
  isDisabled.value = true
}
function tuifang(data) {
  proxy.$modal
    .confirm('是否确认离店？')
    .then(function () {
      return confirmCheckOut(data.houseId)
    })
    .then(() => {
      getList()
      getStatusNum()
      proxy.$modal.msgSuccess('离店成功')
    })
    .catch(() => {})
}
function gengxin(data, command) {
  changeHouseStatus({ houseId: data.houseId, houseStatus: command }).then(
    (res) => {
      proxy.$modal.msgSuccess('状态更新成功')
      getList()
      getStatusNum()
    }
  )
}

function handleDelete(row, index) {
  if (row.recordId) {
    proxy.$modal
      .confirm('是否确认移除此人员？')
      .then(function () {
        return deleteCheckInPeople({
          recordId: row.recordId,
          houseId: form.value.houseId
        })
      })
      .then(() => {
        form.value.hotelCheckRecordList.splice(index, 1)
        proxy.$modal.msgSuccess('移除成功')
        getList()
      })
      .catch(() => {})
  } else {
    form.value.hotelCheckRecordList.splice(index, 1)
  }
}

function addPeople() {
  form.value.hotelCheckRecordList.push({
    idCard: '',
    phone: '',
    realName: '',
    updateIdentify: 1
  })
}
function getStatusNum() {
  getHouseStatusNumber().then((res) => {
    houseStatusNumObj.value = res.data.reduce((acc, item) => {
      acc[item.type] = item.num
      return acc
    }, {})
  })
}

/** 查询房型设置列表 */
function getList() {
  loading.value = true
  houseAllList({
    floorId: floorId.value == 0 ? null : floorId.value,
    houseTypeId: houseTypeId.value == 0 ? null : houseTypeId.value
  }).then((response) => {
    houseList.value = response.data
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    houseId: null,
    createTime: null,
    hotelCheckRecordList: []
  }
}

function toLocalISOString(dateString) {
  const date = new Date(dateString)

  const pad = (num, size = 2) => String(num).padStart(size, '0')

  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从 0 开始
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  const milliseconds = pad(date.getMilliseconds(), 3)

  // 获取本地时区偏移（分钟），并转换为 "+/-HH:mm" 格式
  const timezoneOffset = -date.getTimezoneOffset() // 偏移为正值时是 UTC+
  const sign = timezoneOffset >= 0 ? '+' : '-'
  const offsetHours = pad(Math.floor(Math.abs(timezoneOffset) / 60))
  const offsetMinutes = pad(Math.abs(timezoneOffset) % 60)

  return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}${sign}${offsetHours}:${offsetMinutes}`
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['checkInHotelRef'].validate((valid) => {
    if (valid) {
      if (isDisabled.value) {
        const formParams = JSON.parse(JSON.stringify(form.value))
        formParams.hotelCheckRecordList =
          form.value.hotelCheckRecordList.concat(
            deleteHotelCheckRecordList.value
          )
        updateHouseRecord({ ...formParams, createTime: null }).then(
          (response) => {
            proxy.$modal.msgSuccess('登记成功')
            open.value = false
            getList()
            getStatusNum()
          }
        )
      } else {
        const createTime = toLocalISOString(form.value.createTime)
        addHouseRecord({ ...form.value, createTime }).then((response) => {
          proxy.$modal.msgSuccess('登记成功')
          open.value = false
          getList()
          getStatusNum()
        })
      }
    }
  })
}
let readIndex = 0
function readCard(index) {
  if (!isconncet) {
    ElMessage.error('未连接读卡服务')
  } else {
    readIndex = index
    let paramTimeOut = 10000 // 超时时间(毫秒)
    paramTimeOut = 'timeout=' + paramTimeOut
    var parameterAll = paramTimeOut
    let val = '03?' + parameterAll
    websockets.send(val)
  }
}

function OcrRecognition() {
  if (!isconncet) {
    // 1. 创建websockets对象，参数为服务器websockets地址
    let hostname = '127.0.0.1'
    var url = `ws:${hostname}:9001`
    websockets = new WebSocket(url)

    //监听连接状态的变化
    websockets.onopen = (event) => socketChange()

    //监听接收消息的情况
    websockets.onmessage = (res) => {
      if (res.data == 'failed to obtain ID card information') {
        ElMessage.error('身份信息读取失败')
        return
      }
      var alldata = res.data.split('|')
      if (alldata.length >= 17) {
        form.value.hotelCheckRecordList[readIndex].realName = alldata[3]
        form.value.hotelCheckRecordList[readIndex].idCard = alldata[8]
      } else {
        ElMessage.error(res.data)
      }
    }

    //监听关闭时的状态变化
    websockets.onclose = (event) => socketChange()
  }
}

function socketChange() {
  let state = websockets.readyState

  let statusArr = {
    0: '正在连接',
    1: '已建立连接',
    2: '正在关闭连接',
    3: '已关闭连接'
  }
  console.log(statusArr[state])

  if (1 == state) {
    isconncet = true
  } else {
    isconncet = false
  }
}

getFloorAll()
getHouseTypeAll()

getList()
getStatusNum()
</script>
<style lang="scss">
.house-info {
  .el-form-item__label {
    font-size: 18px !important;
  }
  .el-form-item__content {
    font-size: 18px !important;
  }
}
.dengji-table {
  .el-table__inner-wrapper:before {
    height: 0px;
  }
}
</style>
<style scoped lang="scss">
.house-list {
  .house-item {
    width: 200px;
    height: 100px;
    border: 1px solid #eee;
    border-radius: 4px;
    .actions {
      img {
        width: 27px;
        height: 27px;
        margin: 0 6px;
        cursor: pointer;
      }
    }
  }
}
</style>
